package com.ukao.cashregister.ui.login;


import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.hardware.display.DisplayManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.TextView;

import com.tencent.bugly.beta.Beta;
import com.ukao.cashregister.R;
import com.ukao.cashregister.base.BaseActivity;
import com.ukao.cashregister.bean.SearchHistorysBean;
import com.ukao.cashregister.consts.SaveParamets;
import com.ukao.cashregister.db.SearchHistorysDao;
import com.ukao.cashregister.doubleScreen.DoubleScreenService;
import com.ukao.cashregister.ui.MainActivity;
import com.ukao.cashregister.utils.CheckUtils;
import com.ukao.cashregister.utils.L;
import com.ukao.cashregister.utils.T;
import com.ukao.cashregister.widget.ShapedImageView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;
import me.yokeyword.fragmentation.SupportFragment;


public class LoginActivity extends BaseActivity {


    public static final int FIRST = 0;
    public static final int SECOND = 1;
    @BindView(R.id.left_control_menu_netstat)
    ImageView leftControlMenuNetstat;
    @BindView(R.id.left_control_menu_shopname)
    TextView leftControlMenuShopname;
    @BindView(R.id.left_control_menu_icon)
    ShapedImageView leftControlMenuIcon;
    @BindView(R.id.left_control_menu_username)
    TextView leftControlMenuUsername;
    @BindView(R.id.left_control_menu_play_money)
    Button leftControlMenuPlayMoney;
    @BindView(R.id.left_control_menu_remind)
    Button leftControlMenuRemind;
    @BindView(R.id.left_control_menu_remind_count)
    TextView leftControlMenuRemindCount;
    @BindView(R.id.left_control_menu_exit)
    Button leftControlMenuExit;
    @BindView(R.id.card_btn)
    RadioButton cardBtn;
    @BindView(R.id.account_btn)
    RadioButton accountBtn;
    @BindView(R.id.left_layout)
    ImageView leftLayout;
    @BindView(R.id.right_layout)
    ImageView rightLayout;
    @BindView(R.id.fl_tab_container)
    FrameLayout flTabContainer;


    private SupportFragment[] mFragments = new SupportFragment[2];
    private WifiReceiver mReceiver;
    private SearchHistorysDao dao;
    private ArrayList<SearchHistorysBean> historywordsList;
    private String strSerialNum;
    private String code;
    private WifiManager mWifiManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //startScreenService();
        if (SaveParamets.isLogin()){

          startActivity(new Intent(this,MainActivity.class));
            finish();
        return;
        }
        setContentView(R.layout.fragment_login);
        ButterKnife.bind(this);
        setCode();
        SupportFragment firstFragment = findFragment(SwipingCardragment.class);
        if (firstFragment == null) {
            mFragments[FIRST] = SwipingCardragment.newInstance("", "");
            mFragments[SECOND] = AccountLoginFragment.newInstance("", "");

            loadMultipleRootFragment(R.id.fl_tab_container, FIRST,
                    mFragments[FIRST],
                    mFragments[SECOND]);

        } else {
            mFragments[FIRST] = firstFragment;
            mFragments[FIRST] = findFragment(SwipingCardragment.class);
            mFragments[SECOND] = findFragment(AccountLoginFragment.class);

        }
        if (!CheckUtils.isMIUIDevices()){
            Beta.checkUpgrade(false,false);/*不提示正在检查更新，2不弹提示*/
        }
        initView();

    }



    /**
     * 开启双屏并且检测是否有是双屏
     */
    private void startScreenService() {
        DisplayManager mDisplayManager = (DisplayManager) getSystemService(Context.DISPLAY_SERVICE);
        Display[] displays = mDisplayManager.getDisplays();
        if (displays.length>1){
            Intent service = new Intent(this, DoubleScreenService.class);
            startService(service);
            bindService(service, screenConn, Context.BIND_AUTO_CREATE);
        }

    }
    private ServiceConnection screenConn = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {



        }
    };

    @Override
    protected void initView() {
        mWifiManager= (WifiManager) this.getSystemService(Context.WIFI_SERVICE);

        leftControlMenuIcon.setVisibility(View.INVISIBLE);
        leftControlMenuShopname.setVisibility(View.INVISIBLE);
        leftControlMenuUsername.setVisibility(View.INVISIBLE);
        leftControlMenuExit.setVisibility(View.INVISIBLE);



    }

    private void setCode() {
        code = "";
        dao = new SearchHistorysDao(this);
        historywordsList = dao.findAll();

        for (SearchHistorysBean searchHistorysBean : historywordsList) {
            if (!searchHistorysBean.historyword.equals("first")) {
                code = code + searchHistorysBean.historyword;

                try {

                    JSONObject mJSONObject = new JSONObject(searchHistorysBean.historyword);
                    strSerialNum = mJSONObject.getString("serialNum");

                } catch (JSONException e) {


                }
            }
        }

        if (!CheckUtils.isEmpty(strSerialNum)) {

            SaveParamets.setCode(strSerialNum);
        }

        L.i("GlobalConsts.CODE="+strSerialNum);
    }


    @OnCheckedChanged({R.id.card_btn, R.id.account_btn})
    public void OnCheckedChanged(CompoundButton view, boolean checked) {
        if (checked) {
            switch (view.getId()) {
                case R.id.card_btn:

                    leftLayout.setVisibility(View.VISIBLE);
                    rightLayout.setVisibility(View.GONE);
                    showHideFragment(mFragments[0], mFragments[1]);

                    break;
                case R.id.account_btn:

                    rightLayout.setVisibility(View.VISIBLE);
                    leftLayout.setVisibility(View.GONE);
                    showHideFragment(mFragments[1], mFragments[0]);
                    break;
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        leftControlMenuNetstat.setImageResource(mWifiManager.isWifiEnabled() ? R.drawable.left_control_menu_wifi : R.drawable.left_control_menu_no_wifi);
        registerReceiver();
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(mReceiver);
    }

    /**
     * 注册wifi 广播
     */
    private void registerReceiver() {
        mReceiver = new WifiReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
        filter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(mReceiver, filter);
    }

    @OnClick({R.id.left_control_menu_netstat})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.left_control_menu_netstat:
                Intent  mIntent=new Intent(this,WifiActivity.class);
                startActivity(mIntent);

                break;

        }


    }

    @Override
    public void onBackPressedSupport() {

        if (getSupportFragmentManager().getBackStackEntryCount() > 1) {
            pop();
        }
    }


    private class WifiReceiver extends BroadcastReceiver {
        protected static final String TAG = "ukao";


        @Override
        public void onReceive(Context context, Intent intent) {

            if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {// wifi连接上与否
                Log.d(TAG, "网络已经改变");

                NetworkInfo info = intent
                        .getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
                if (info.getState().equals(NetworkInfo.State.DISCONNECTED)) {
                    Log.d(TAG, "wifi已经断开");
                    leftControlMenuNetstat.setImageResource(R.drawable.left_control_menu_no_wifi);

                } else if (info.getState().equals(NetworkInfo.State.CONNECTING)) {
                    Log.d(TAG, "正在连接...");
                    leftControlMenuNetstat.setImageResource(R.drawable.left_control_menu_no_wifi);

                } else if (info.getState().equals(NetworkInfo.State.CONNECTED)) {
                    WifiManager wifiManager = (WifiManager) context
                            .getSystemService(Context.WIFI_SERVICE);
                    WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                    Log.d(TAG, "连接到网络：" + wifiInfo.getBSSID());
                    leftControlMenuNetstat.setImageResource(R.drawable.left_control_menu_wifi);
                }

            } else if (intent.getAction().equals(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION)) {
                int error = intent.getIntExtra(WifiManager.EXTRA_SUPPLICANT_ERROR,
                        0);
                Log.e("ukao", "error=" + error);
                switch (error) {

                    case WifiManager.ERROR_AUTHENTICATING:
                        Log.d(TAG, "密码认证错误Code为：" + error);
                        T.show("密码认证错误");
                        break;

                    default:
                        break;
                }

            }
        }

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
     //   unbindService(screenConn);
    }
}
